package com.itheima.controller;

import com.itheima.common.*;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author: lcc
 * @Desc: 用户模块-控制器
 * @Date: 2022/6/5 15:49
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 功能描述: 客户-登录验证码
     *
     * @param user
     * @return : com.itheima.common.Result
     */
    @PostMapping("/sendMsg")
    public Result sendVerifyCode(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        //1、调用Service，获取验证码
        Integer verifyCode = userService.sendVerifyCode(phone);
        //2、验证码存入session（为了进行验证码比对）
        //session.setAttribute(SmsConstant.USER_VERIFY_CODE+phone,verifyCode+"");
        //2、验证码存入redis（为了进行验证码比对）
        redisTemplate.opsForValue().set(SmsConstant.USER_VERIFY_CODE + phone, verifyCode + "");
        return new Result(Code.OK, MessageConstant.VERIFYCODE_SEND_SUCCESS);
    }

    /***
     * 功能描述: 用户登录
     * @param map
     * @param session
     * @param response
     * @return : com.itheima.common.Result
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map map, HttpSession session, HttpServletResponse response) {
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        //1.校验手机号、验证码
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(code)) {
            return new Result(Code.ERROR, MessageConstant.USER_LOGIN_ERROR);
        }

        String redisCode = (String) redisTemplate.opsForValue().get(SmsConstant.USER_VERIFY_CODE + phone);
        if (!code.equals(redisCode)) {
            return new Result(Code.ERROR, MessageConstant.USER_LOGIN_ERROR);
        }


        //String sessionCode = (String) session.getAttribute(SmsConstant.USER_VERIFY_CODE + phone);
       // redisTemplate.opsForHash().putAll(SmsConstant.USER_VERIFY_CODE + phone, map);



        //调用service，判断用户是否已经存在
        Long userId = userService.login(phone);
        //登录成功：往session中存储客户登录信息；给客户端浏览器签发令牌
        // 把用户ID，存储到redis中

        String redisId = EmployeeConstant.USER_LOGIN + phone;
        redisTemplate.opsForValue().set(redisId,userId);
        //把手机号,存储到redis中
        redisTemplate.opsForValue().set(EmployeeConstant.USER_PHONE,phone);
        //  session.setAttribute(sessionId,userId);
        // 往cookie中存储数据,把cookie写回浏览器
        Cookie cookie = new Cookie(EmployeeConstant.USER_TOKEN, redisId);
        cookie.setMaxAge(EmployeeConstant.TOKEN_EXPIRE);
        cookie.setDomain("localhost");
        cookie.setPath("/");
        response.addCookie(cookie);
        return new Result(Code.OK, MessageConstant.LOGIN_SUCCESS);
    }

    /**
     * 功能描述: 登出功能
     *
     * @param session
     * @param response
     * @return : com.itheima.common.Result
     */
    @PostMapping("/loginout")
    public Result logout(HttpServletRequest request, HttpSession session, HttpServletResponse response) {
        //1.获取要删除的session的key（sessionId）
        String sId = null;
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return new Result(Code.ERROR, MessageConstant.LOGOUT_ERROR);
        }
        for (Cookie cookie : cookies) {
            if (EmployeeConstant.USER_TOKEN.equals(cookie.getName())) {
                sId = cookie.getValue();
            }
        }
        //2.从session中删除指定的数据
        //session.removeAttribute(sId);
        redisTemplate.delete(sId);
        //3.从cookie删除指定的数据
        Cookie cookie = new Cookie("token", "");
        cookie.setDomain("localhost");
        cookie.setPath("/");
        cookie.setMaxAge(EmployeeConstant.TOKEN_DEAD);//令牌失效
        response.addCookie(cookie);
        return new Result(Code.OK, MessageConstant.LOGOUT_SUCCESS);
    }
}

